import 'package:flutter_admin/pages/common/cry/cry_all.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/udt_tb_docmentstock_odoo_api.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/constants/constant.dart';
import 'package:flutter_admin/models/odoo/udt_tb_docmentstock.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/odoo/udt_tb_docmentstock/select_docmenttype_list.dart';
import 'package:flutter_admin/utils/store_util.dart';
import '../../../generated/l10n.dart';

class UdtTbDocmentstockEdit extends StatefulWidget {
  UdtTbDocmentstockEdit({this.udtTbDocmentstock});

  final UdtTbDocmentstock? udtTbDocmentstock;

  @override
  _UdtTbDocmentstockEditState createState() => _UdtTbDocmentstockEditState();
}

class _UdtTbDocmentstockEditState extends State<UdtTbDocmentstockEdit> {
  late UdtTbDocmentstock udtTbDocmentstock;
  bool? isAdd;

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  //存放区域名称
  late List<SelectOptionVO> areaList = [];
  //存放位置名称
  late List<SelectOptionVO> locationList = [];

  @override
  void initState() {
    super.initState();
    this.isAdd = widget.udtTbDocmentstock == null;
    var department = StoreUtil.read(Constant.KEY_CURRENT_USER_INFO)[0]["department_id"];
    this.udtTbDocmentstock = widget.udtTbDocmentstock ?? UdtTbDocmentstock(departmentId: department[0].toString(),departmentName: department[1].toString());
    _loadSelectVO();
  }

  _loadSelectVO() async{
    areaList = await DynamicDataApi.getModelSelect(active: false,model: "dms.documentarea",name: "areaname",key: "department_id",val: int.parse(udtTbDocmentstock.departmentId!));
    if(udtTbDocmentstock.areaId!=null)
      locationList = await DynamicDataApi.getModelSelect(active:false,model: "dms.documentlocation",name: "locationname",key: "area_id",operator: "=",val: int.parse(udtTbDocmentstock.areaId!));
    setState(() { });
  }

  _selectDocumenttype() {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: SelectDocmenttypeList(),
      ),
    ).then((v) async{
      if (v != null) {
        formKey.currentState!.save();
        udtTbDocmentstock.documenttypeId=v["id"].toString();
        udtTbDocmentstock.documenttypeName=v["documenttypename"].toString();
        udtTbDocmentstock.documentno = null;
        try{
          udtTbDocmentstock.documentno = await UdtTbDocmentstockOdooApi.getDocumentno(departmentId: int.parse(udtTbDocmentstock.departmentId!),documenttypeId:v["id"]);
        }catch(e){}
        setState(() { });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            label: '所属部门',
            value: udtTbDocmentstock.departmentName,
            onSaved: (v) => {udtTbDocmentstock.departmentName = v},
            enable: false,
          ),
          CryInput(
            label: '档案项目',
            value: udtTbDocmentstock.documenttypeName,
            onSaved: (v) => {udtTbDocmentstock.documenttypeName = v},
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
            onTap: () => _selectDocumenttype(),
          ),
          CryInput(
            label: '档案盒编号',
            enable: false,
            value: udtTbDocmentstock.documentno,
            onSaved: (v) => {udtTbDocmentstock.documentno = v},
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInput(
            label: '档案盒名称',
            value: udtTbDocmentstock.documentname,
            onSaved: (v) => {udtTbDocmentstock.documentname = v},
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),

          CrySelect(
            label: '存放区域',
            dataList: areaList,
            value: udtTbDocmentstock.areaId,
            onSaved: (v) => {udtTbDocmentstock.areaId = v},
            onChange: (v) async {
              if(udtTbDocmentstock.areaId!=v){
                formKey.currentState!.save();
                udtTbDocmentstock.areaId=v;
                udtTbDocmentstock.locationId=null;
                locationList = [];
                locationList = await DynamicDataApi.getModelSelect(active:false,model: "dms.documentlocation",name: "locationname",key: "area_id",operator: "=",val: int.parse(v));
                formKey.currentState!.save();
                setState(() { });
              }
            },
          ),
          CrySelect(
            label: '存放位置',
            dataList: locationList,
            value: udtTbDocmentstock.locationId,
            onSaved: (v) => {udtTbDocmentstock.locationId = v},
          ),
          CryInput(
            label: '备注',
            value: udtTbDocmentstock.remark,
            onSaved: (v) => {udtTbDocmentstock.remark = v},
          ),
        ],
      ),
    );
    var buttonBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: S.of(context).save,
          onPressed: () {
            FormState form = formKey.currentState!;
            if (!form.validate()) {
              return;
            }
            form.save();
            if(udtTbDocmentstock.status == null ){
              udtTbDocmentstock.status = '0';
            }
            UdtTbDocmentstockOdooApi.saveOrUpdate(udtTbDocmentstock.toOdooMap()).then((ResponseBodyApi res) {
              // 对接完善
              if (!res.success!) {
                // CryUtils.message(res.message!);
                return;
              }
              Navigator.pop(context, true);
              CryUtils.message(S.of(context).saved);
            });
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        )
      ],
    );
    var result = Scaffold(
      appBar: AppBar(
        title: Text(this.isAdd! ? S.of(context).add : S.of(context).modify),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [form],
        ),
      ),
      bottomNavigationBar: buttonBar,
    );
    return SizedBox(
      width: 650,
      height: 650,
      child: result,
    );
    // return result;
  }
}